//
//  ComposeViewController.swift
//  sinaOnceAgain
//
//  Created by 王相超 on 16/2/25.
//  Copyright © 2016年 chuanzhi. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    
    
    @objc private func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    
    //更新约束
    @objc private func selectPicture() {
        
       pictureSelector.view.snp_updateConstraints { (make) -> Void in
        make.height.equalTo(ScreenHeight / 3 * 2)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    
    
    @objc private func send() {
        
        var urlString = "2/statuses/update.json"
        let parameters = ["access_token": UserAccountViewModel.sharedAccountViewModel.access_token,"status": textView.text]
        
        if pictureSelector.imageList.count > 0 {
            
            
            let imageData = UIImagePNGRepresentation(self.pictureSelector.imageList.first!)!
            
             urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
           
            
        HTTPClient.sharedClient.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
            
            formData.appendPartWithFileData(imageData, name: "pic", fileName: "xxxx", mimeType: "application/octet-stream")
            }, progress: nil, success: { (_, result) -> Void in
                print(result)
                
                
                self.close()
            }, failure: { (_, error) -> Void in
                print(error)
        })
        
        
        
        }else{
            
            HTTPClient.sharedClient.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
                
                if error != nil {
                    
                    SVProgressHUD.showErrorWithStatus("发布微博失败,请检查网络")
                    return
                }
                
                self.close()
            }
            
        }
        
    }
    
    override func viewDidLoad() {
        
        
        super.viewDidLoad()
        
        setNavBar()
        
        view.backgroundColor = UIColor.whiteColor()
        
        setTextView()
        setBottomToolBar()
        setPictureSelector()
        
        //注册通知
        registerNotification()
    }
    
    //实现通知的方法
    @objc private func keyBoardWillChange(noti: NSNotification) {
        
        print(noti)
        
        //在动画闭包中   修改底部工具条的位置  更新底部约束
        // 1.获取动画运行的时间
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //键盘结束的frame cgrect 是结构体  结构体需要转换成NSValue对象才能够添加到字典中
        let rect = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let height = -ScreenHeight + rect.origin.y
        
        //在动画闭包中更新约束
        UIView.animateWithDuration(duration) { () -> Void in
            
            //更新约束
            self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(height)
            })
            
            //强制刷新页面
            self.view.layoutIfNeeded()
        }
        
        
    }
    
    
    private func registerNotification() {
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    //移除通知
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    //懒加载textView视图
    private lazy var textView: UITextView = {
        
        let tv = UITextView()
        
        //qtv.text = "输入新鲜事...."
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.lightGrayColor()
        tv.backgroundColor = UIColor.greenColor()
        tv.alwaysBounceVertical = true
        //下面这个属性的前提是  滚动视图可以滚动
        tv.keyboardDismissMode = .OnDrag
        
        tv.delegate = self
        
        return tv
    }()
    
    
    //底部工具条
    private lazy var toolBar: UIToolbar = UIToolbar()
    private lazy var placeHolder: UILabel = UILabel(text: "请输入新鲜事", fontSize: 18, textColor: UIColor(white: 0.7, alpha: 1))
    
    
    //图片选择控制器
    private lazy var pictureSelector: PictureSelectorViewController = PictureSelectorViewController()
    
}


//textView代理方法

extension ComposeViewController: UITextViewDelegate {
    
    
    func textViewDidChange(textView: UITextView) {
        
        //如果有文本  隐藏占位文本
        //反之   回复默认状态
        placeHolder.hidden = textView.hasText()
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}




//MARK: UI设置相关的分类
extension ComposeViewController {
    
    
    private func setPictureSelector() {
        
        //添加视图控制器
        self.addChildViewController(pictureSelector)
        
        //添加视图控制器的视图
        self.view.addSubview(pictureSelector.view)
        
        //将toolbar 移动到最顶层
        self.view.bringSubviewToFront(toolBar)
        
        //设置约束
        pictureSelector.view.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(self.view.snp_left)
            make.right.equalTo(self.view.snp_right)
            make.bottom.equalTo(self.view.snp_bottom)
            make.height.equalTo(0)
        }
        
    }
    
    //底部工具条
    private func setBottomToolBar() {
        
        view.addSubview(toolBar)
        
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            //默认高度是44
        }
        
        //设置toolBar  内部的按钮
        var  items = [UIBarButtonItem]()
        //配置字典类型
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background"]]
        
        for item in itemSettings {
            
            //实例化UIBarButtonItem对象  默认的渲染色 是蓝色 并且不能够设置高亮状态的图片
            let imageName = item["imageName"]
            let btn = UIButton(backImageName: nil, imageName: imageName!)
            if let actionName = item["actionName"] {
                
                
                //添加点击事件
                btn.addTarget(self, action: Selector(actionName), forControlEvents: UIControlEvents.TouchUpInside)
//                btn.addTarget(self, action:actionName, forControlEvents: .TouchUpInside)
            }
            
            let barItem = UIBarButtonItem(customView: btn)
            
            //将对象添加到数组中
            items.append(barItem)
            
            //添加弹簧的item
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        
        items.removeLast()
        
        //设置工具条的按钮数组对象
        toolBar.items = items
    }
    
    //添加子视图
    private func setTextView() {
        
        view.addSubview(textView)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.view.snp_top)
            make.left.equalTo(self.view.snp_left)
            make.right.equalTo(self.view.snp_right)
            make.height.equalTo(ScreenHeight / 3)
            
            //添加占位文本
            textView.addSubview(placeHolder)
            //设置占位的约束
            placeHolder.snp_makeConstraints(closure: { (make) -> Void in
                make.top.equalTo(textView.snp_top).offset(8)
                make.left.equalTo(textView.snp_left).offset(5)
            })
        }
        
    }
    
    
    //设置导航条
    private func setNavBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        
        //初始的时候  设置发布按钮不能交互
        navigationItem.rightBarButtonItem?.enabled = false
        
        //自定义导航条 titleview
        let weiboTitle = UILabel(text: "发布微博", fontSize: 18, textColor: UIColor.darkGrayColor())
        
        let nameLable = UILabel(text: UserAccountViewModel.sharedAccountViewModel.userName ?? "", fontSize: 15, textColor: UIColor.lightGrayColor())
        
        //titleView  默认是nil 要实现添加的操作  需要赋值
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        
        navigationItem.titleView = titleView
        navigationItem.titleView?.addSubview(weiboTitle)
        navigationItem.titleView?.addSubview(nameLable)
        
        //设置约束
        weiboTitle.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        
        nameLable.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.bottom.equalTo(titleView.snp_bottom)
        }
        
    }
    
    
    
    
    
}





